var SERVER_LOC = "https://yulekeji.cn/hanshu/api";
var IsWaiting = false;
var HaveStatusTop = false;
var FirstBackPressed = null;

/**
 * 在此填入每个webview在顶层时状态栏应当显示的颜色
 */
var StatusBarColors = {
	'Question': 'light',
	'Lecture': 'light',
	'Message': 'light',
	'Mine': 'light',
	'UserIndex': 'light',
	'ImgView': '000000',
	'Settings': 'light',
	'Ques': 'light',
	'QuesAsk': 'light',
	'SetEdu': 'light',
	'SetCV': 'light',
};
var InTrans = false;

//-----------------------------
//  实现状态栏颜色根据页面转变(见Index/index.html)
//-----------------------------
function GetTheme() {
	let root = document.documentElement;
	let personalCenterHeaderImg = 'none';
	root.style.setProperty('--color-black', 'white');
	root.style.setProperty('--color-white', 'black');
	root.style.setProperty('--color-yellow', '#FDD100');
	root.style.setProperty('--color-gray-black', '#F0F0F0');
	root.style.setProperty('--color-gray-dark', '#DBDBDB');
	root.style.setProperty('--color-gray-light', '#343434');
	root.style.setProperty('--color-gray-white', '#111111');
	root.style.setProperty('--personal-center-header-img', personalCenterHeaderImg);
}

function GetStatusBarColor() {
	StatusBarColors[plus.webview.getLaunchWebview().id] = 'light';
	/* 内部工具函数 */
	function str2Color(str) {
		return parseInt(str, 16);
	}

	function color2Str(colorR, colorG, colorB) {
		return color2Str_2(colorR * 65536 + colorG * 256 + colorB);
	}

	function color2Str_2(color) {
		let res = color.toString(16);
		for (let i = 0; res.length < 6; ++i)
			res = '0' + res;
		return res.substr(0, 6);
	}

	// 取当前wvid
	var wvid;
	try {
		wvid = plus.webview.getTopWebview().id;
	} catch (err) {
		return false;
	}

	var colorName = StatusBarColors[wvid.split('-')[0]];
	// 无法获取新颜色时退出
	if (colorName == null) {
		return false;
	}
	// 生成新旧颜色
	var lastColor, nowColor;
	if (colorName == "dark") {
		nowColor = str2Color("484848");
	} else if (colorName == "light") {
		nowColor = str2Color("FFFFFF");
	} else {
		nowColor = str2Color(colorName);
	}
	lastColor = str2Color(plus.navigator.getStatusBarBackground().substr(1));
	if (nowColor == lastColor) {
		return;
	}
	// 锁定同时可操作的进程
	if (InTrans) {
		return;
	}
	InTrans = true;
	// 分解目标颜色
	let r1 = nowColor / 65536 % 256;
	let g1 = nowColor / 256 % 256;
	let b1 = nowColor % 256;
	// 根据目标颜色深度判断文字颜色
	if (r1 + g1 + b1 <= 400) {
		plus.navigator.setStatusBarStyle("light");
	} else {
		plus.navigator.setStatusBarStyle("dark");
	}
	plus.navigator.setStatusBarBackground('#' + color2Str_2(nowColor));
	InTrans = false;
}

function GetStatusTop() {
	//GetTheme();
	GetStatusBarColor();
	// 后退键
	if (plus.webview.currentWebview() !== plus.webview.getLaunchWebview() && plus.webview.currentWebview().opener() !=
		plus.webview.getLaunchWebview()) {
		plus.key.addEventListener('backbutton', function() {
			ThisBack();
		});
	}
	var statusbarHeight = parseInt(plus.storage.getItem('statusbarHeight'));

	if (HaveStatusTop) return;
	HaveStatusTop = true;
	try {
		let oldHeight = parseFloat(getComputedStyle(QUERY(':root')[0]).getPropertyValue('--header-height'));
		if (TAG('header').length == 0) {
			oldHeight = 0;
		}
		oldHeight *= screen.width / 100;
		let newHeight = oldHeight + statusbarHeight;
		QUERY(':root')[0].style.setProperty('--header-height', newHeight + '');
		TAG('header')[0].style.height = newHeight + 'px';
		//let oldPadding = getComputedStyle(CLASS('content')[0]).getPropertyValue('padding-top');
		CLASS('content')[0].style.paddingTop = newHeight + 'px';
	} catch (e) {}
}

function WVTop() {
	if (!plus.navigator.hasNotchInScreen)
		return -plus.storage.getItem('statusbarHeight');
	return 0;
}

function ID(id) {
	return document.getElementById(id);
}

function TAG(tag) {
	return document.getElementsByTagName(tag);
}

function CLASS(cls) {
	return document.getElementsByClassName(cls);
}

function QUERY(qry) {
	return document.querySelectorAll(qry);
}

function CallAJAX(loc, data, success, error, contentType, protocol, noLocPreFix = false) {
	contentType = contentType ? contentType : "application/json";
	protocol = protocol ? protocol : "POST";
	//data = typeof data === 'string' 全面json化后使用
	loc = noLocPreFix ? loc : ("/tools/" + loc);
	let xhr = new plus.net.XMLHttpRequest();
	xhr.onreadystatechange = function() {
		if (xhr.readyState != 4)
			return;
		if (xhr.status == 200) {
			let data = JSON.parse(xhr.responseText);
			if (data["res"] == 0) {
				plus.nativeUI.alert("您的账号已在其他设备登录过, 请确认账号安全后重新登录!", "账号异常");
				plus.runtime.restart();
			} else {
				if (typeof success === 'function')
					success(data);
			}
		} else {
			if (typeof error === 'function')
				error();
			else
				plus.nativeUI.toast("请检查网络连接, 或稍后重试");
		}
	}
	xhr.timeout = 8000;

	xhr.open(protocol, SERVER_LOC + loc);
	xhr.setRequestHeader('Content-Type', contentType);
	if (typeof data == "string")
		xhr.send(data);
	else
		xhr.send(JSON.stringify(data));
}

function CheckUpdate(callback, error) {
	let now = plus.storage.getItem('version'); //plus.runtime.version;
	// 手动CallAJAX
	CallAJAX("/checkUpdate/latest", "", function(data) {
		DontWait();
		console.log(now + "  " + data["version"]);
		var latest = data["version"];
		if (now == latest) {
			if (typeof callback === 'function')
				callback();
			return;
		}
		// 显示更新提示(内容, CB, {标题, 按钮})
		plus.nativeUI.confirm("更新内容：\n" + data["context"], function(e) {
			if (e.index == 1) {
				plus.nativeUI.toast('请及时更新程序哟');
			} else {
				switch (plus.os.name) {
					case "Android":

						plus.runtime.openURL(SERVER_LOC + data["loc"][0]);
						break;
					case "iOS":
						plus.runtime.openURL(data["loc"][1]);
						break;
				}
			}
			plus.runtime.quit();
		}, {
			"title": "发现新版本(" + data["version"] + ")",
			"buttons": ["确认", "取消"],
		});
	}, function() {
		if (typeof error === 'function')
			error();
	}, "text/plain", "GET", true);
}

function ReLogin(showConfirm) {
	showConfirm = showConfirm ? showConfirm : false;
	var doReLogin = function() {
		plus.storage.setItem("userHash", "NULL");
		plus.runtime.restart();
	}
	if (showConfirm) {
		plus.nativeUI.confirm('您确定要退出登录吗? 这将退出您当前的账号', function(e) { // callback
			if (e.index == 0)
				doReLogin();
		}, {
			"title": '退出登录',
			"buttons": ["确认", "取消"],
		});
	} else {
		doReLogin();
	}
}


/**
 * 刷新userInfo后执行callback中的内容, 
 * 需要获取新userInfo， 请使用plus.storage.getItem('userInfo')
 * @param {Function} callback(phoneNo)
 */
function RefreshUserInfo(callback) {
	var phoneNo;
	var userHash = plus.storage.getItem("userHash");
	DoWait();
	//AJAX: phoneNo用于接下来的通信
	CallAJAX("getPhoneNoByUserHash", userHash, function(data) { // success函数
		if (data["res"] == "ok") {
			phoneNo = data["phoneNo"];
			//AJAX: 通过phoneNo获取当前用户的所有信息
			CallAJAX("getUserInfo", {
				"phoneNo": phoneNo,
				"infoReqs": "all"
			}, function(data2) { // success函数
				if (data2["res"] == "ok") {
					//AJAX: 通过用户的eduId获取学校和院系名称
					CallAJAX("getEduDetail", {
						'eduId': data2["userInfo"]["uEduId"],
					}, function(data3) {
						if (data3["res"] == "ok") {
							data2["userInfo"]["uEduSchoolName"] = data3["eduDetail"][0];
							data2["userInfo"]["uEduDeptName"] = data3["eduDetail"][1];
							//更新全局存储"userInfo"并填充页面信息
							plus.storage.setItem("userInfo", JSON.stringify(data2["userInfo"]));

							callback(phoneNo);
						}
						DontWait();
					}, function() {
						DontWait();
					});
				}
			}, function() {
				DontWait();
			});
		}
	}, function() {
		DontWait();
	});
}

/**
 * 刷新院校列表后执行callback中的内容, 
 * 需要获取新院校列表信息 请使用plus.storage.getItem('eduList')
 * @param {Function} callback()
 */
function RefreshEduList(callback) {
	DoWait();
	//AJAX: 通过phoneNo获取当前用户的所有信息
	CallAJAX("listEdu", {}, function(data) { // success函数
		if (data["res"] == "ok")
			plus.storage.setItem('eduList', JSON.stringify(data["countries"]));
		DontWait();
		callback();
	}, function() {
		DontWait();
	});
}

/* 内部函数, 呼叫某页面的refreshPage(). 
   现在用在ThisClose/ThisBack系列函数中 */
function WVRefresh(wv) {
	if (wv) {
		wv.evalJS(`
			try{ refreshPage(); }
			catch(e) {}
		`);
	}
}

/**
 * BeforeBack类函数应该在自定义Back()、自定义Close()
 *   以及plus.key的backbutton事件中统一写入
 * 但这里的MyBeforeBack是仅限首页和首页子页面才使用的, 
 *   因此只需绑定backbutton事件
 */
function MyBeforeBack() {
	//首次按键，提示‘再按一次退出应用’
	if (!FirstBackPressed) {
		FirstBackPressed = new Date().getTime();
		plus.nativeUI.toast('再按一次退出应用');
		setTimeout(function() {
			FirstBackPressed = null;
		}, 1000);
	} else {
		if (new Date().getTime() - FirstBackPressed < 1000) {
			plus.runtime.quit();
		}
	}
};

function ThisClose() {
	WVRefresh(plus.webview.currentWebview().opener());
	plus.webview.currentWebview().close();
}

function ThisHide() {
	WVRefresh(plus.webview.currentWebview().opener());
	plus.webview.currentWebview().hide();
}

function ThisBack() {
	if (plus.webview.currentWebview().canBack()) {
		plus.webview.currentWebview().back();
		WVRefresh(plus.webview.currentWebview());
	} else {
		ThisClose();
	}
}

function BackCheck(callback) {
	plus.nativeUI.confirm('您确定要返回吗？这可能会丢失已编辑的数据。', function(e) { // callback
		if (e.index == 0 && typeof callback === 'function')
			callback();
	}, {
		"title": '返回上一页',
		"buttons": ["确认", "取消"],
	});
}

function DoShow(view, action, time) {
	action = action ? action : "fade-in";
	time = time ? time : 200;
	view.show(action, time);
	DontWait();
}

function DoWait(timeout) {
	timeout = timeout ? timeout : 1000;
	IsWaiting = true;
	setTimeout(function() {
		if (IsWaiting == true)
			plus.nativeUI.showWaiting();
	}, timeout);
}

function DontWait() {
	IsWaiting = false;
	plus.nativeUI.closeWaiting();
}

function Date2String(date) {
	var stringTime = [date.getMonth() + 1, date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()]
	for (var i = 0; i < 5; i++)
		stringTime[i] = stringTime[i] < 10 ? '0' + stringTime[i] : stringTime[i]
	return date.getFullYear().toString() + stringTime[0] + stringTime[1] + stringTime[2] + stringTime[3] + stringTime[4];
}

function String2Date(dateString, isFmt) {
	isFmt = isFmt ? isFmt : false;
	var pattern = /(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/;
	var formatedString = dateString.replace(pattern, '$1/$2/$3 $4:$5:$6');
	if (isFmt)
		return formatedString;
	else
		return (new Date(formatedString));
}

/**
 * 在Pick等操作前, 必须初始化一个FileInputDOM
 * @param {DOM} parentDOM
 * @param {function} callback
 * @param {string} acceptType 默认为"image/*"
 * @author DHC
 */
function InitFileInputDOM(parentDOM, callback, acceptType) {
	if (document.getElementById('FILEINPUT') === null) {
		acceptType = acceptType ? acceptType : "image/*";
		parentDOM.innerHTML += '<input id="FILEINPUT" style="display:none;" type="file" accept="' + acceptType + '">';
	}
	if (typeof callback === 'function') {
		callback();
	}
}

/**
 * 通过inputDOM(默认为"#FILEINPUT")拾取文件, 
 * 将文件的base64字符串传入callback.
 * 
 * @param {function} callback
 * @param {DOM} DOM 默认为"#FILEINPUT"
 * @author DHC
 * @modified 2020/4/27
 */
function Pick(callback, DOM) {
	DOM = DOM ? DOM : document.getElementById('FILEINPUT');
	DOM.onchange = function() {
		try {
			if (DOM.files[0]) {
				FiletoDataURL(DOM.files[0], function(res) {
					if (typeof callback === 'function') {
						callback(res);
					}
				});
			}
		} catch (e) {
			console.log(e);
		}
	}
	DOM.click();
}

/**
 * 将input的file转换为base64编码
 */
function FiletoDataURL(file, callback) {
	var reader = new FileReader();
	reader.onloadend = function(e) {
		try {
			let res = e.target.result;
			ZipImgFile(res, {
				width: 300
			}, function(res1) {
				res = res1;
				if (typeof callback === 'function') {
					callback(res);
				}
			});
		} catch (ex) {
			console.log(ex);
		}
	};
	reader.readAsDataURL(file);
};

/**
 * @param {String} base64
 * @param {Object} config
 * @param {Function} callback
 * 压缩base64格式的图片文件, 通过callback(res)返回压缩后的base64字符串res
 * config中包含width, height, quality(0~1)三个属性, 可以任意省略.
 */
function ZipImgFile(base64, config, callback) {
	var img = new Image();
	img.src = base64;
	img.onload = function() {
		// 默认按比例压缩, 除非同时指定宽和高
		var scale = this.width / this.height;
		var w = config.width || this.width;
		var h = config.height || (w / scale);
		if (config.height && !config.width) { // 只指定height时的弥补操作
			w = h * scale;
		}
		//生成canvas
		var canvas = document.createElement('canvas');
		var ctx = canvas.getContext('2d');
		// 创建属性节点
		var anw = document.createAttribute("width");
		var anh = document.createAttribute("height");
		anw.nodeValue = w;
		anh.nodeValue = h;
		canvas.setAttributeNode(anw);
		canvas.setAttributeNode(anh);
		ctx.drawImage(this, 0, 0, w, h);
		// 回调函数返回base64的值
		var ext = base64.substring(base64.indexOf("/") + 1, base64.indexOf(";")).toLowerCase();
		callback(canvas.toDataURL('image/' + ext, config.quality || 0.8));
	}
}

/**
 * 上传文件, callback(data)中的data为upload接口的返回数据
 * @param {string} base64
 * @param {function} callback
 */
function Upload(base64, callback) {
	//console.log(base64.split(';').shift().split(':').pop().toLowerCase());
	CallAJAX('upload', {
		'userHash': plus.storage.getItem('userHash'),
		'resource': base64.split(',').pop(),
		'type': base64.split(';').shift().split(':').pop().toLowerCase()
	}, function success(data) {
		callback(data);
	}, function error() {
		console.log("Upload failed.");
	});
}

/**
 * CheckLength_inner
 *  返回值
 *    'min': 字数不够
 *    'max': 字数超限
 *    'fit': 字数合适
 * @author DHC
 */
function CheckLength_inner(text, maxlen, minlen) {
	minlen = minlen ? minlen : 1;
	text = text.replace(/(^s*)|(s*$)/g, "").trim();
	if (text.length > maxlen) {
		return 'max';
	} else if (text.length < minlen) {
		return 'min';
	} else {
		return 'fit';
	}
}
/**
 * 检查长度是否合格
 * @param {string} name
 * @param {string} text
 * @param {number} maxlen
 * @param {number} minlen
 * @author DHC
 */
function CheckLength(name, text, maxlen, minlen) {
	var res = CheckLength_inner(text, maxlen, minlen);
	if (res == 'max') {
		plus.nativeUI.alert(name + '字数最长为' + maxlen + ', 请检查!', '字数超限');
		return false;
	} else if (res == 'min') {
		plus.nativeUI.alert(name + '字数最短为' + minlen + ', 请检查!', '字数不够');
		return false;
	} else {
		return true;
	}
}

/**
 * 关注或取关
 * @param {string} phoneNo
 * @param {function} callback
 * @author DHC
 */
function DoFollow(phoneNo, callback) {
	let tUserHash = plus.storage.getItem('userHash');
	CallAJAX('doFollow', {
		'userHash': tUserHash,
		'followeeId': phoneNo,
	}, callback);
}

/* 数字转字符串补零 */
function Pad(num, n) {
	var len = num.toString().length;
	while (len < n) {
		num = "0" + num;
		len++;
	}
	return num;
}
